package com.linkstec.loader;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.linkstec.redis.RedisUtil;

public abstract class Loader {
	private static final Logger logger = LogManager.getLogger();
	
	public Loader(String loaderId, String loaderDesc, String sqlId) {
		super();
		this.loaderId = loaderId;
		this.loaderDesc = loaderDesc;
		this.sqlId = sqlId;
	}
	protected String loaderId;
	protected String loaderDesc;
	protected String sqlId;
	protected long costTime;
	protected long loadCount;
	protected boolean ongoing = false;
	protected Map<String, Object> smot_param = new HashMap<String, Object>();
	protected java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	protected void doLoad() throws Exception{
		if (ongoing) {
			logger.info(this.loaderDesc + "加载中");
			return;
		}
	}
	protected void beforeLoadData() throws Exception{
		try {
			Dao.getInstance().openConnInThread();
			
			smot_param.put("LOADID", this.loaderId);
			smot_param.put("CURRENTTHREADID", Thread.currentThread().getId());
			smot_param.put("BEGINTIME", sdf.format(new java.util.Date()));
			smot_param.put("CREATER", this.loaderDesc);
			Dao.getInstance().insertUpdateSQL("insert.Begin.SMOT_ENGSTATUS",
					smot_param);
		} catch (Exception e) {
			throw e;
		}
	}
	protected String afterLoadData() throws Exception{
		ongoing = false;;
		StringBuilder msg = new StringBuilder();
		try {
			msg.append(loaderDesc).append("完成，共加载").append(loadCount).append("条记录,耗时")
					.append(costTime / 60000).append("分钟")
					.append(costTime / 1000 % 60).append("秒")
					.append(costTime % 1000).append("毫秒");

			String redisKey = "LASTUPDATE_" + this.loaderId;
			smot_param.put("ENDTIME", sdf.format(new java.util.Date()));
			smot_param.put("UPDATER", this.loaderDesc);
			smot_param.put("REMARK", "加载完成数量：" + loadCount);
			Dao.getInstance().insertUpdateSQL("update.End.SMOT_ENGSTATUS",
					smot_param);
			RedisUtil.set(redisKey,
					new SimpleDateFormat("yyyyMMddHHmmSS").format(new Date()));
			
		} catch (Exception e) {
			throw e;
		} finally {
			Dao.getInstance().closeConnInThread();
		}
		return msg.toString();
	}
}